package it.cpyx.appengine.server;

import it.cpyx.appengine.server.data.utils.LabelDataUtils;
import it.cpyx.appengine.server.data.utils.TextDataUtils;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class SaveTextDataServlet  extends HttpServlet {

	private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest req, HttpServletResponse resp){
    	getOrPost(req,resp);
    }
    
    private void getOrPost(HttpServletRequest req, HttpServletResponse resp) {
    	try{
	       	UserService userService = UserServiceFactory.getUserService();
	        User user = userService.getCurrentUser();
	
	        Text content = new Text(req.getParameter("content"));
	        String password = req.getParameter("password");
	        String manualId=req.getParameter("manualId").trim();
	        String title=req.getParameter("title").trim();
	        String label=req.getParameter("labels").trim();
	        if(password.equals("")){
	        	password=null;
	        }

	        //replace not word char with "-"
			Pattern replace = Pattern.compile("[^\\w]");
			Matcher matcher2 = replace.matcher(manualId);
			manualId=matcher2.replaceAll("-");
			//^home
			
			String uniqueManualUrlExtension=TextDataUtils.generateUniqueUrlExtension(manualId);

			Long id=TextDataUtils.insert(uniqueManualUrlExtension, content, password, title, user);
			
			Pattern replace1 = Pattern.compile("[^\\w]");
			Matcher matcher21 = replace1.matcher(label);
			label=matcher21.replaceAll("-");
			String [] labels=label.split("-");
	        
	        for(int i=0;i<labels.length;i++){
	        	if(!labels[i].equals("")){
		        	Long lblId=LabelDataUtils.addTextDataToLabelDataIfNotExist(labels[i], id);
		        	TextDataUtils.addLabelDataIdToTextData(id, lblId);
	        	}
	        }
	        try{
				resp.sendRedirect("/"+uniqueManualUrlExtension);
			}catch(IOException e){
				e.printStackTrace();
			}
    	}catch (Exception e) {
    		System.err.println(e.toString());
		}
        
		
    }

}
